package eip.chapter9.splitaggregate.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mule.impl.MuleMessage;
import org.mule.routing.outbound.AbstractMessageSplitter;
import org.mule.umo.UMOMessage;
import org.mule.umo.endpoint.UMOEndpoint;

import eip.chapter9.splitaggregate.InformationRequest;

/**
 * Splits information from the incoming request
 * 
 * @author nl24167
 */
public class InformationSplitter extends AbstractMessageSplitter {
	
	private final static Log LOG = LogFactory.getLog(InformationSplitter.class);
	
	private final static String USER_ENDPOINT_NAME = "user-information";
	private final static String HOTEL_ENDPOINT_NAME = "hotel-information";
	private final static String RESERVATION_ENDPOINT_NAME = "reservation-information";
	
	private InformationRequest toProcess;
	
	/**
	 * Initialize this component. 
	 */
	@Override
	protected void initialise(UMOMessage message) {
		super.initialise(message);
		multimatch = false;
		toProcess = (InformationRequest) message.getPayload();
	}

	/**
	 * This method is called for each of the defined endpoints. Based on the 
	 * name of the endpoint we determine which part of the message to send.
	 */
	@Override
	protected UMOMessage getMessagePart(UMOMessage msg, UMOEndpoint endpoint) {
		LOG.info("Splitting incoming request for endpoint: " + endpoint.getName());
		UMOMessage resultMsg = null;
		
		if (endpoint.getName().equals(USER_ENDPOINT_NAME)) {
			resultMsg = new MuleMessage(toProcess.getUserID());
		} else if (endpoint.getName().equals(HOTEL_ENDPOINT_NAME)) {
			resultMsg = new MuleMessage(toProcess.getHotelID());
		} else if (endpoint.getName().equals(RESERVATION_ENDPOINT_NAME)) {
			resultMsg = new MuleMessage(new String[] {toProcess.getUserID(),toProcess.getHotelID()});
		} else {
			LOG.warn("Unknown endpoint: " + endpoint.getName() + ". No part send to: " + endpoint);
		}
		
		// set some correlation properties
		resultMsg.setCorrelationId(toProcess.getRequestID());
		resultMsg.setCorrelationGroupSize(3);
		
		return resultMsg;
	}

}
